//
//  GeneticViewController.m
//  Disp_Controller
//
//  Created by peterluck on 14/11/14.
//  Copyright (c) 2014年 peterluck. All rights reserved.
//
#import "GeneticViewController.h"

@interface GeneticViewController ()

@end

@implementation GeneticViewController
@synthesize Genetic_closeBtn;
@synthesize Genetic_webViewForSelectDate;
@synthesize Genetic_timer;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

/*
 * 返回主界面
 * 关联PID页面的返回按钮
 */
- (IBAction)ExitGeneticShowPage:(id)sender
{
#if DC_PID_DEBUG
    NSLog(@"BUTTON_EVENT_DEBUG:****** 点击返回按钮!!!!!!!! ******\n");
#endif
    /*关闭定时器*/
    [Genetic_timer invalidate];
    Genetic_timer = nil;
    /*返回主界面*/
    UINavigationController* naviController = (UINavigationController*)[[UIApplication sharedApplication] keyWindow].rootViewController;
    [naviController popViewControllerAnimated:YES];
}

/*
 * 关联"switch"按钮
 * 控制曲线的开始和停止
 */
- (IBAction)Genetic_Start_Stop_SwitchButton:(id)sender
{
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
#if DC_PID_DEBUG
        NSLog(@"BUTTON_EVENT_DEBUG:****** 选择\"开始\"!!!!!!!! ******\n");
#endif
        /*开启定时器，持续给曲线页面传送数据*/
        Genetic_timer = [NSTimer
                     scheduledTimerWithTimeInterval: 0.25
                     target: self
                     /*
                      * selector用在形成无限循环监听端口
                      *                  add by songxin
                      *                  14/11/09
                      */
                     selector: @selector(Comp_updateData)
                     userInfo: nil
                     repeats: YES];
    }else {
#if DC_PID_DEBUG
        NSLog(@"BUTTON_EVENT_DEBUG:****** 选择\"停止\"!!!!!!!! ******\n");
#endif
        /*关闭定时器*/
        [Genetic_timer invalidate];
        Genetic_timer = nil;
    }
}

- (void)viewDidLoad
{
    /*
     UIInterfaceOrientation orientation = [UIDevice currentDevice].orientation;
     
     //如果CurveViewController.xib是竖屏的话，进行if中的操作。
     if (UIDeviceOrientationIsPortrait(orientation) || orientation == UIDeviceOrientationUnknown)
     {
     if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
     {
     [[UIDevice currentDevice] performSelector:@selector(setOrientation:)
     withObject:(id)UIDeviceOrientationLandscapeRight];
     }
     }
     */
    
    CGRect webFrame = self.view.frame;
    webFrame.origin.x = -156;//-400;
    webFrame.origin.y = -378;
    
    Genetic_webViewForSelectDate = [[UIWebView alloc] initWithFrame:webFrame];
    Genetic_webViewForSelectDate.delegate = self;
    Genetic_webViewForSelectDate.scalesPageToFit = NO; //取消曲线图自适应屏幕大小;
    Genetic_webViewForSelectDate.opaque = NO;
    Genetic_webViewForSelectDate.backgroundColor = [UIColor clearColor];
#if DC_PID_DEBUG
    NSLog(@"DATA_DEBUG:****** The UIViewAutoresizingFlexibleWidth is:[%lu] ******\n",(unsigned long)UIViewAutoresizingFlexibleWidth);
#endif
    Genetic_webViewForSelectDate.autoresizingMask = UIViewAutoresizingNone;//(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    [self.view addSubview:Genetic_webViewForSelectDate];
    
    //所有的资源都在source.bundle这个文件夹里
    NSString* htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"GENETIC_source.bundle/index.html"];
    
    NSURL* url = [NSURL fileURLWithPath:htmlPath];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [Genetic_webViewForSelectDate loadRequest:request];
    
    
    /* Delete by songxin
     int trueWidth = self.view.frame.size.width;
     if (trueWidth < self.view.frame.size.height && ![UIApplication sharedApplication].statusBarHidden)
     {
     trueWidth = self.view.frame.size.height + MIN([UIApplication sharedApplication].statusBarFrame.size.height,[UIApplication sharedApplication].statusBarFrame.size.width);
     }
     
     CGRect closeBtnFrame = CGRectMake(trueWidth - 70, 0, 70, 20);
     closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     [closeBtn setFrame:closeBtnFrame];
     [closeBtn setTitle:@"close" forState:UIControlStateNormal];
     [closeBtn addTarget:self action:@selector(closePage) forControlEvents:UIControlEventTouchUpInside];
     [closeBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
     [self.view addSubview:closeBtn];
     [self.view bringSubviewToFront:closeBtn];
     */
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)closePage
{
    UINavigationController* naviController = (UINavigationController*)[[UIApplication sharedApplication] keyWindow].rootViewController;
    [naviController popViewControllerAnimated:YES];
}

/*
 *    这个函数是住循环函数，功能最多，最复杂！！！！！！！！
 *    这个函数下一个版本要
 *       1.用于fork一个子进程后由子进程exec一个Socket通信进程。
 *       2.用在读取Socket通信进程接受到的数据文件
 *                        add by songxin
 *                        14/11/09
 */
-(void)Comp_updateData
{
    //取得当前时间，x轴
    NSDate* nowDate = [[NSDate alloc]init];
    NSTimeInterval nowTimeInterval = [nowDate timeIntervalSince1970] * 1000;
    [nowDate release];
    
    //随机温度，y轴 假数据，下一个版本要替换成真实数据
    int temperature = [self getRandomNumber:20 to:100];
    
#if DC_PID_DEBUG
    NSLog(@"DATA_DEBUG:****** The simulation data is:[%d] ******\n",temperature);
#endif
    
    /*向web绘图界面发出数据*/
    NSMutableString* jsStr = [[NSMutableString alloc] initWithCapacity:0];
    [jsStr appendFormat:@"updateData(%f,%d)",nowTimeInterval,temperature];
    
    [Genetic_webViewForSelectDate stringByEvaluatingJavaScriptFromString:jsStr];
}

//获取一个随机整数，范围在[from,to），包括from，不包括to
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from  + (arc4random() % (to - from + 1)));
}
#pragma mark - delegate of webview
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIDeviceOrientationIsLandscape(interfaceOrientation);
}
#ifdef __IPHONE_6_0
-(BOOL)shouldAutorotate
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    return UIDeviceOrientationIsLandscape(orientation);
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
#endif
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [Genetic_closeBtn release];
    [Genetic_webViewForSelectDate release];
    [super dealloc];
}
@end